package com.jack.hhitseat.task;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.jack.hhitseat.bean.User;
import com.jack.hhitseat.service.HttpClient;
import com.jack.hhitseat.service.impl.LogServiceImpl;
import com.jack.hhitseat.service.impl.LoginServiceImpl;
import com.jack.hhitseat.service.impl.UserServiceImpl;
import com.jack.hhitseat.utils.AipOcrUtil;
import com.jack.hhitseat.utils.MyUtils;

@Component
@Controller
//@EnableScheduling   // 开启定时任务
//@EnableAsync        // 开启多线程
public class MyTask {
	@Autowired
	HttpClient httpClient;
	@Autowired
	private UserServiceImpl userService;
	@Autowired
	private LogServiceImpl logServiceImpl;
	@Autowired
	private LoginServiceImpl loginServiceImpl;
	private final Logger logger = LoggerFactory.getLogger(MyTask.class);
	private final static String KEY = "0";
	private final static  String BOOK_URL = "http://seat.hhit.edu.cn/ClientWeb/pro/ajax/reserve.aspx?" +
			"&dev_id={dev_id}" + "&type={type}" + "&start={start}" + "&end={end}" +
			"&start_time={start_time}" + "&end_time={end_time}"+"&number={number}" + "&act={act}" +
			"&_={_}"; 
	private static Map<String, String> sessionMap = new HashMap<>();
	private static List<User> users = new ArrayList<>();
	
	//定时登录
//	@Scheduled(cron = "00 20 05 * * ?")
    public void getSession() {
		init();
    }
	
	//假定提前请求的验证码都正确、然后直接抢首选座位
//	@Scheduled(cron = "59 29 05 * * ? ")		//抢座时间。
	public void bookSeat() {
		logger.warn("******启动百度ai预约====");
		String yyrq = MyUtils.getNextDate(); 

		Date d = MyUtils.String2Date(yyrq);
		String sjc = (System.currentTimeMillis()+60000)+"";
		  
		Calendar cal = Calendar.getInstance();
		cal.setTime(d);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;	//预约日期是星期几
		
		for (User u : users) {
		    String stuNum = u.getStuNum();
			if(logServiceImpl.isSuccess(stuNum) > 0) {
				System.out.println("continue==="+ stuNum);
				continue;
			}
			String[] seats = u.getSeat().split(",");
			String session = sessionMap.get(stuNum);
			Map<String, Object> qzParparamMap = new HashMap<String, Object>();

			qzParparamMap.put("type","dev");
			qzParparamMap.put("start",yyrq+"+08:00");
			qzParparamMap.put("start_time","800"); 
			qzParparamMap.put("end",yyrq+"+22:00");		//正常时间
			qzParparamMap.put("end_time","2200");		//正常时间
			qzParparamMap.put("number", KEY);			//万能钥匙Key
			qzParparamMap.put("act","set_resv");
			
			final int COUNT = 5;
			String seatNumb = seats[0].split("=")[0];
			String result = "";
			int i = 0;
	        qzParparamMap.put("dev_id", seatNumb); 
			qzParparamMap.put("_",sjc);
			
			if(w != 3) {
				for (i = 1; i <= COUNT; i++) {
					result = httpClient.qz2(BOOK_URL, session, qzParparamMap);
					if(!result.contains("验证码")) {
						if(result.contains("成功")) {
							logServiceImpl.addLog(stuNum, seatNumb);
							break;
						}else if(result.contains("已有预约")) {
							break;
						}else if(result.contains("不在开放时间")) {
							break;
						}
						logger.warn("【AI】==={}==={}==={}==={}", i, u.getUserName() ,
								result.split("\"msg\":\"")[1].split("\",\"data\":")[0] , seats[0].split("=")[1]);
						break;
					}else {
					    String key = AipOcrUtil.getResult(AipOcrUtil.getCode(httpClient.yzm2Api(session)));
					    qzParparamMap.put("number", key);
					}
				}
			}else {
				for (i = 1; i <= COUNT; i++) {
					qzParparamMap.put("start",yyrq+"+08:00");
					qzParparamMap.put("start_time","800"); 
					qzParparamMap.put("end",yyrq+"+12:00");
					qzParparamMap.put("end_time","1200");
					result = httpClient.qz2(BOOK_URL, session, qzParparamMap);
					qzParparamMap.put("start",yyrq+"+18:00");
					qzParparamMap.put("start_time","1800"); 
					qzParparamMap.put("end",yyrq+"+22:00");		
					qzParparamMap.put("end_time","2200");		
					result = httpClient.qz2(BOOK_URL, session, qzParparamMap);
					if(!result.contains("验证码")) {
						if(result.contains("成功")) {
							logServiceImpl.addLog(stuNum, seatNumb);
							break;
						}else if(result.contains("已有预约")) {
							break;
						}else if(result.contains("不在开放时间")) {
							logger.warn("图书馆系统未开放！！！");
							break;
						}
						logger.warn("【AI】==={}==={}==={}==={}", i, u.getUserName() ,
								result.split("\"msg\":\"")[1].split("\",\"data\":")[0] , seats[0].split("=")[1]);
						break;
					}else {				
					    String key = AipOcrUtil.getResult(AipOcrUtil.getCode(httpClient.yzm2Api(session)));
					    qzParparamMap.put("number", key);
					}
				}
			}
		}
	}
	
/***************************************************************************/
    
    public void init() {
    	sessionMap.clear();
    	users.clear();
//    	users = userService.getAllUserByDo(100, 20);
//    	users = userService.getAllUserByDo();
    	users = userService.getAllUserByStuNums();
//System.out.println("-----------开始登陆");
    	Iterator<User> it = users.iterator();
    	while(it.hasNext()){
    		User user = it.next();
    		String sission = login2wx(user);
    		//登录正常
			if(!sission.equals("LOGIN_ERR")) {
				String stuNum = user.getStuNum();
				//获取放入学号和Session
				sessionMap.put(stuNum, sission);
			}else {
				it.remove();
//				user.setIsdo(0);
//				userService.updateUser(user);
//				Login login = new Login();
//				login.setUserId(Integer.parseInt(user.getStuNum()));
//				login.setIp(user.getUserName()+"***密码错误！！");
//				login.setLoginTime(MyUtils.getNowDateTime());
//				loginServiceImpl.addLogin(login);
			}
    	}
    	logger.warn("本次抢座人数==={}", users.size());
    }
    
    public String login2wx(User user) {
    	final int COUNT = 500;
    	 String url = "http://seat.hhit.edu.cn/ClientWeb/pro/ajax/login.aspx"; 
		  MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>();
		  String sjc = (System.currentTimeMillis()+120000)+"";
		  
		  params.add("act","dlogin");
		  params.add("number", KEY);
		  params.add("id", user.getStuNum()); 
		  params.add("pwd", user.getPassword()); 
		  params.add("role", "512");
		  params.add("_nocache", sjc);
		  
		ResponseEntity<String> response =  HttpClient.login2wx(url, null, params);
		String session = response.getHeaders().toString().split("ASP.NET_SessionId=")[1].split("; path=/; ")[0];
		
		for (int i = 1; i <= COUNT; i++) {
			String body =  response.getBody();
			if(!body.contains("验证码")) {
				if(body.contains("密码")) {
					logger.warn("{}***密码错误！！", user.getStuNum());
					return "LOGIN_ERR";
				} 
				//logger.warn("{}==={}==={}", i, user.getUserName(),session);
				return session;
			} else {
				httpClient.yzm(session);
				response =  HttpClient.login2wx(url, session, params);
			}
		}
		return session;
    }
}
